import Vue from 'vue'
import axios from 'axios'
import {Message} from 'element-ui'

import { getLocal, removeLocal } from '@/utils/local.js'
import router from '@/router/index.js'


// 创建axios实例
const _fetch = axios.create({
  baseURL: process.env.VUE_APP_URL,  // 配置基url
  withCredentials: true  // 跨域时,携带cookie
})
Vue.prototype.$axios = _fetch;  // 将axios挂载到全局Vue


// Add a request interceptor
_fetch.interceptors.request.use(function (config) {
  // Do something before request is sent
  // 请求头中添加token
  const tokenVal = getLocal('token');
  if (tokenVal) {
    config.headers.token = tokenVal;
  }

  return config;
}, function (error) {
  // Do something with request error

  return Promise.reject(error);
});

// Add a response interceptor
_fetch.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  if (response.data.code === 200) {
    return response;
  } else if (response.data.code === 206) {
    // token过期,清除token
    removeLocal('token');
    // 跳转登录界面
    router.push('/login');
    Message.error(response.data.message);
    return Promise.reject(response.data.message);
  } else {
    Message.error(response.data.message);
    return Promise.reject(response.data.message);
  }
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  return Promise.reject(error);
});


export default _fetch;